import { useState } from 'react'
import { Table, Input, Button, message } from 'antd'
import styles from './index.less'

const columns = [
  {
    title: '标签名',
    dataIndex: 'tagName',
    key: 'tagName',
    width: 250
  },
  {
    title: '属性名',
    dataIndex: 'attrName',
    key: 'attrName',
    width: 250
  }
]


/**
 * 可编辑的指定标签的属性数组
 */
const EditableAttrs = (props) => {
  const { value = [], onChange } = props
  const [tagName, setTagName] = useState('')
  const [attrName, setAttrName] = useState('')

  const handleAdd =() => {
    if (value.some(l => l.tagName === tagName && l.attrName === attrName)) {
      message.error('指定规则已存在，无需添加')
      return
    }
    onChange([...value, {
      tagName,
      attrName
    }])
  }

  /**
   * 标签名变更
   */
  const handleChangeTagName = (e) => {
    setTagName(e.target.value)
  }

  /**
   * 属性名变更
   */
  const handleChangeAttrName = (e) => {
    setAttrName(e.target.value)
  }

  return <div className={styles.container}>
    <div className={styles.header}>
      <Input size="small" value={tagName} className={styles.input} onChange={handleChangeTagName} placeholder="请输入标签名" />
      <Input size="small" value={attrName} className={styles.input} onChange={handleChangeAttrName} placeholder="请输入属性名" />
      <Button type="primary" size="small" onClick={handleAdd}>添加</Button>
    </div>
    <Table locale={{ emptyText: '暂无数据' }} pagination={false} className={styles.table} columns={columns} dataSource={value} rowKey={(item) => (item.tagName + item.attrName)} />
  </div>

}

export default EditableAttrs
